import axios from 'axios'
import { Toast } from 'vant'
import { localGet } from './local'
const fetch = axios.create({
  baseURL: 'http://localhost:1337'
})
// 添加请求拦截器
fetch.interceptors.request.use(
  function (config) {
    if (config.needToken) {
      const token = localGet('token')
      if (token) {
        config.headers.authorization = `Bearer ${localGet('token')}`
      }
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
fetch.interceptors.response.use(
  function (response) {
    // console.log('拦截器', response)
    const code = response.data.code
    if (code === 200) {
      return response.data
    } else if (code === 400 || code === 401 || code === 403) {
      Toast.fail(response.data.message)
      // console.log(response.data.message)
      return Promise.reject(new Error(response.data.message))
    }
  },
  function (error) {
    return Promise.reject(error)
  }
)
export default fetch
